<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\common\Common;
use app\common\Pay;
use app\common\UserService;
use app\job\Task;
use app\model\Goods;
use app\model\GoodsAssess;
use app\model\GoodsClass;
use app\model\GoodsCoupon;
use app\model\GoodsOrders;
use app\model\GoodsOrdersDetail;
use app\model\GoodsShopcar;
use app\model\GoodsSpec;
use app\model\User;
use app\model\UserCoupon;
use app\tool\Random;
use GuzzleHttp\Client;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\Exception;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;
use think\Request;

class GoodsController extends BaseController
{
	
	protected $order_timeout = 60 * 15;//订单超时时间
	
	
	/**
	 * 类目
	 * @return void
	 */
	function class()
	{
		$rows = GoodsClass::where(['pid' => 0])->order(['id' => 'desc'])->select();
		$this->writeJson($rows);
	}
	
	/**
	 * 类目
	 * @return void
	 */
	function classDetail()
	{
		$id = $this->request->get('id/d');
		if (empty($id)) {
			$this->writeJson(0, '参数错误');
		}
		$rows = GoodsClass::where(['pid' => $id])->order(['id' => 'desc'])->select();
		$this->writeJson($rows);
	}
	
	#首页
	function index()
	{
		$price = $this->request->get('price');
		$sales = $this->request->get('sales');
		$class_ids = GoodsClass::column('id');
		$rows = Goods::where(['recommen' => 1])
			->whereIn('class_id',$class_ids)
			->withMin(['spec' => 'min_price'], 'price')
			->when(!empty($price), function (Query $query) use ($price) {
				$query->order(['min_price' => $price]);
			})
			->when(!empty($sales), function (Query $query) use ($sales) {
				$query->order(['sales' => $sales]);
			})
			->order(['id'=>'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	#搜索
	function search()
	{
		$price = $this->request->get('price');
		$sales = $this->request->get('sales');
		$keyword = $this->request->get('keyword');
		$rows = Goods::withMin(['spec' => 'min_price'], 'price')
			->when(!empty($price), function (Query $query) use ($price) {
				$query->order(['min_price' => $price]);
			})
			->when(!empty($sales), function (Query $query) use ($sales) {
				$query->order(['sales'=>$sales]);
			})
			->when(!empty($keyword), function (Query $query) use ($keyword) {
				$query->whereLike('name', '%' . $keyword . '%');
			})
			->order(['id'=>'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	#列表
	function list()
	{
		$first_class_id = $this->request->get('first_class_id/d'); #必填
		$second_class_id = $this->request->get('second_class_id/d');
		$price = $this->request->get('price');
		$sales = $this->request->get('sales');
		$rows = Goods::withMin(['spec' => 'min_price'], 'price')
			->when(!empty($second_class_id), function (Query $query) use ($second_class_id) {
				$query->where(['class_id' => $second_class_id]);
			}, function (Query $query) use ($first_class_id) {
				$second_class_ids = GoodsClass::where(['pid' => $first_class_id])->column('id');
				$query->whereIn('class_id', $second_class_ids);
			})
			->when(!empty($price), function (Query $query) use ($price) {
				$query->order(['min_price' => $price]);
			})
			->when(!empty($sales), function (Query $query) use ($sales) {
				$query->order(['sales' => $sales]);
			})
			->order(['id'=>'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	#详情
	function detail()
	{
		
		$goods_id = $this->request->get('goods_id/d');
		$address = \app\model\Config::getFieldByName('address','value');
		
		$row = Goods::withMin(['spec' => 'min_price'], 'price')->with(['spec', 'user_collect' => function (Query $query) {
			$query->where(['user_id' => $this->user_id]);
		}])->filter(function ($data) use($address) {
			$coupon = GoodsCoupon::where(function (Query $query) use ($data) {
				$query->whereOr('goods_id', $data->id)->whereOr('scene', 2);
			})->where('num', '>', 0)->filter(function ($data) {
				$UserCoupon = UserCoupon::where(['coupon_id' => $data->id, 'user_id' => $this->user_id])->find();
				if ($UserCoupon) {
					$data->receive = 1;
				} else {
					$data->receive = 0;
				}
			})->select();
			$data->coupon = $coupon;
			$data->address = $address;
			$data->shopcar_count = GoodsShopcar::where(['user_id' => $this->user_id])->count();
			$res = Common::getWechatQrcode('pages/index/goodsDetail',$data->id);
			$data->qrdata = 'data:image/png;base64,' . base64_encode($res);
		})->findOrFail($goods_id);
		UserService::changeUserFoot($goods_id, $this->user_id);//增加足迹
		$this->writeJson($row);
	}
	
	#评价列表
	function assessList()
	{
		$goods_id = $this->request->get('goods_id/d');
		$type = $this->request->get('type/d');
		$rows = GoodsAssess::where(['goods_id' => $goods_id])
			->with(['user','spec'])
			->when(!empty($type), function (Query $query) use ($type) {
				if ($type == 1) {
					$query->where('score', 5);
				}
				if ($type == 2) {
					$query->whereBetween('score', [2, 4]);
				}
				if ($type == 3) {
					$query->where('score', 1);
				}
				if ($type == 4) {
					$query->where('images', '<>', '');
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		foreach ($rows as $row){
			if ($row->anonymous == 1){
				$row->user->nickname = '匿名';
			}
		}
		$assess_count = GoodsAssess::where(['goods_id' => $goods_id])->count();//总数
		$good_count = GoodsAssess::where(['goods_id' => $goods_id])->where('score', 5)->count();//好评
		$just_count = GoodsAssess::where(['goods_id' => $goods_id])->whereBetween('score', [2, 4])->count();//中评
		$bad_count = GoodsAssess::where(['goods_id' => $goods_id])->where('score', 1)->count();//差评
		$images_count = GoodsAssess::where(['goods_id' => $goods_id])->where('images', '<>', '')->count();//有图
		$this->writeJson(['count' => $assess_count, 'good_count' => $good_count, 'just_count' => $just_count, 'bad_count' => $bad_count, 'images_count' => $images_count, 'list' => $rows]);
	}
	
	/**
	 * 收藏
	 */
	function collect()
	{
		$goods_id = $this->request->post('goods_id/d');
		$ret = UserService::collect($goods_id, $this->user_id);
		$this->writeJson($ret);
	}
	
	/**
	 * 领取优惠券
	 * @return void
	 */
	function receiveCoupon()
	{
		$id = $this->request->post('id/d'); //优惠券ID
		$coupon = GoodsCoupon::findOrFail($id);
		if ($coupon->num == 0) {
			$this->writeJson(0, '优惠券被领完了');
		}
		
		$row = UserCoupon::where(['user_id' => $this->user_id, 'coupon_id' => $id])->find();
		if ($row) {
			$this->writeJson(0, '不能重复领取');
		}
		$coupon->num -= 1;
		$coupon->save();
		UserCoupon::create([
			'user_id' => $this->user_id,
			'coupon_id' => $id,
			'coupon' => $coupon,
			'expiretime' => strtotime('+' . $coupon->expire_day . 'day', time())
		]);
		$this->writeJson();
	}
	
	/**
	 * 检查优惠券
	 * @return void
	 */
	function checkCoupon()
	{
		$spec_id = $this->request->get('spec_id/d');
		$num = $this->request->get('num/d');
		$spec = GoodsSpec::findOrFail($spec_id);
		
		$goods_amount = $num * $spec->price;//总金额
		$coupon = UserCoupon::where(['user_id' => $this->user_id, 'status' => 1])->select();//全部优惠券
		$valid = [];//有效优惠券
		$invalid = [];//无效优惠券
		foreach ($coupon as $k) {
			$detail = $k->coupon;
			if ($k->expiretime <= time()) {
				$k->msg = '优惠券已过期';
				$invalid[] = $k;
				continue;
			}
			if ($detail['scene'] == 1) {
				//指定商品
				if ($detail['goods_id'] == $spec->goods_id) {
					if ($detail['type'] == 1) {
						if ($detail['with_amount'] > $goods_amount) {
							//不满足
							$k->msg = '订单金额不满足满减金额';
							$invalid[] = $k;
						} else {
							//满足
							$k->msg = '666';
							$valid[] = $k;
						}
					} else {
						$k->msg = '666';
						$valid[] = $k;
					}
				} else {
					$k->msg = '不支持此商品';
					$invalid[] = $k;
				}
			} else {
				if ($detail['type'] == 1) {
					if ($detail['with_amount'] > $goods_amount) {
						//不满足
						$k->msg = '订单金额不满足满减金额';
						$invalid[] = $k;
					} else {
						//满足
						$k->msg = '666';
						$valid[] = $k;
					}
				} else {
					$k->msg = '666';
					$valid[] = $k;
				}
			}
		}
		$this->writeJson(['valid' => $valid, 'invalid' => $invalid]);
	}
	
	/**
	 * 价格计算
	 * @return void
	 */
	function getPrice()
	{
		$spec_id = $this->request->get('spec_id/d');
		$num = $this->request->get('num/d');
		$coupon_id = $this->request->get('coupon_id/d', 0);
		$address = \app\model\Config::getFieldByName('address','value');
		$spec = GoodsSpec::with(['goods'])->findOrFail($spec_id);
		if ($spec->sku < $num) {
			$this->writeJson(0, '商品库存不足');
		}
		$total_amount = bcmul((string)$num,(string)$spec->price,2);//总金额=数量*规格单价
		$coupon_amount = '0'; //优惠券金额
		if (!empty($coupon_id)) {
			$coupon = UserCoupon::findOrFail($coupon_id);
			if ($coupon->expiretime <= time()) {
				$this->writeJson(0, '优惠券已过期');
			}
			if ($coupon->status != 1) {
				$this->writeJson(0, '优惠券已被使用');
			}
			$couponDetail = $coupon->coupon;
			if ($couponDetail['scene'] == 1) {
				if ($couponDetail['goods_id'] != $spec->goods_id) {
					$this->writeJson(0, '此优惠券不属于本商品');
				}
			}
			if ($couponDetail['type'] == 1 && $couponDetail['with_amount'] > $total_amount) {
				$this->writeJson(0, '订单金额不满足满减金额');
			}
			$coupon_amount = $couponDetail['amount'];
			
		}
		
		$pay_amount =bcsub($total_amount,$coupon_amount,2);
		if ($pay_amount <= 0) {
			$pay_amount = 0.01;
		}
		$this->writeJson(['spec' => $spec,'address'=>$address, 'pay_amount' => $pay_amount, 'coupon_amount' => $coupon_amount, 'total_amount' => $total_amount]);
	}
	
	/**
	 * 创建订单
	 * @return void
	 */
	function createOrder()
	{
		$take_delivery_id = $this->request->post('take_delivery_id/d'); //提货人
		$spec_id = $this->request->post('spec_id/d'); //规格
		$num = $this->request->post('num/d', 1); //数量
		$coupon_id = $this->request->post('coupon_id/d', 0); //优惠券
		$pay_type = $this->request->post('pay_type/d'); //支付方式
		$mark = $this->request->post('mark', ''); //备注
		if (empty($take_delivery_id)) {
			$this->writeJson(0, '提货人不能为空');
		}
		
		$spec = GoodsSpec::findOrFail($spec_id);
		$user = User::findOrFail($this->user_id);
		if ($spec->sku < $num) {
			$this->writeJson(0, '商品库存不足');
		}
		//修改库存
		$spec->sku -= 1;
		$spec->save();
		$total_amount = $num * $spec->price;//原价=数量*规格单价+运费
		$coupon_amount = 0; //优惠券金额
		if (!empty($coupon_id)) {
			$coupon = UserCoupon::findOrFail($coupon_id);
			if ($coupon->expiretime <= time()) {
				$this->writeJson(0, '优惠券已过期');
			}
			if ($coupon->status != 1) {
				$this->writeJson(0, '优惠券已被使用');
			}
			$couponDetail = $coupon->coupon;
			if ($couponDetail['scene'] == 1) {
				if ($couponDetail['goods_id'] != $spec->goods_id) {
					$this->writeJson(0, '此优惠券不属于本商品');
				}
			}
			if ($couponDetail['type'] == 1 && $couponDetail['with_amount'] > $total_amount) {
				$this->writeJson(0, '订单金额不满足满减金额');
			}
			$coupon_amount = $couponDetail['amount'];
			//使用优惠券
			$coupon->status = 2;
			$coupon->save();
		}
		
		$pay_amount = $total_amount - $coupon_amount;
		if ($pay_amount <= 0) {
			$pay_amount = 0.01;
		}
		
		$ordersn = Random::ordersn();
		$data = [
			'user_id' => $this->user_id,
			'take_delivery_id' => $take_delivery_id,
			'coupon_id' => $coupon_id,
			'total_amount' => $total_amount, // 原价=商品价格*数量
			'pay_amount' => $pay_amount, //原价-优惠券金额
			'coupon_amount' => $coupon_amount,//优惠券金额
			'order_sn' => $ordersn,
			'mark' => $mark,
		];
		
		// 启动事务
		Db::startTrans();
		try {
			$order = GoodsOrders::create($data);
			$order->detail()->save([
				'goods_id' => $spec->goods_id,
				'spec_id' => $spec_id,
				'amount' => $total_amount,
				'num' => $num,
			]);
			$ret = Pay::pay($pay_type, $pay_amount, $ordersn, '购买商品', 'goods', $user->openid);
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			$this->writeJson(0, $e->getMessage());
		}
		Queue::later($this->order_timeout, Task::class, ['order_id' => $order->id, 'action' => 'goods_order_timeout'], 'task');
		$this->writeJson(['pay' => $ret, 'order_id' => $order->id]);
	}
	
	
	/**
	 * 加入购物车
	 * @return void
	 */
	function shopcarAdd()
	{
		$spec_id = $this->request->post('spec_id/d');
		$num = $this->request->post('num/d', 1);
		$spec = GoodsSpec::findOrFail($spec_id);
		
		$car = GoodsShopcar::where(['user_id' => $this->user_id, 'goods_id' => $spec->goods_id, 'spec_id' => $spec_id])->find();
		if ($car) {
			$car->num += $num;
		} else {
			GoodsShopcar::create([
				'user_id' => $this->user_id,
				'goods_id' => $spec->goods_id,
				'spec_id' => $spec_id,
				'num' => $num,
			]);
		}
		$this->writeJson();
	}
	
	/**
	 * 购物车列表
	 * @return void
	 */
	function shopcarList()
	{
		$rows = GoodsShopcar::where(['user_id' => $this->user_id])
			->with(['goods'=>function (Query $query) {
				$query->with(['spec']);
			}, 'spec'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	/**
	 * 修改购物车
	 * @return void
	 */
	function shopcarEdit()
	{
		$shopcar_id = $this->request->post('shopcar_id/d');
		$num = $this->request->post('num/d', 1);
		$spec_id = $this->request->post('spec_id/d', 0);
		$row = GoodsShopcar::findOrFail($shopcar_id);
		if (!empty($num)) {
			$row->num = $num;
		}
		if (!empty($spec_id)) {
			$row->spec_id = $spec_id;
		}
		$row->save();
		$this->writeJson();
	}
	
	/**
	 * 删除购物车
	 * @return void
	 */
	function shopcarDelete()
	{
		$shopcar_ids = $this->request->post('shopcar_ids');
		$rows = GoodsShopcar::whereIn('id',$shopcar_ids)->select();
		foreach ($rows as $row){
			$row->delete();
		}
		$this->writeJson();
	}
	
	
	/**
	 * 购物车检查优惠券
	 * @return void
	 */
	function shopcarCheckCoupon()
	{
		$shopcar_ids = $this->request->get('shopcar_ids');
		$GoodsShopcar = GoodsShopcar::whereIn('id', $shopcar_ids)->selectOrFail();
		
		$valid = [];//有效优惠券
		$invalid = [];//无效优惠券
		foreach ($GoodsShopcar as $shopcar) {
			$goods_amount = $shopcar->num * $shopcar->spec->price;//总金额
			$coupon = UserCoupon::where(['user_id' => $this->user_id, 'status' => 1])->select();//未使用优惠券
			foreach ($coupon as $k) {
				$detail = $k->coupon;
				if ($k->expiretime <= time()) {
					$k->msg = '优惠券已过期';
					$invalid[] = $k;
					continue;
				}
				if ($detail['scene'] == 1) {
					//指定商品
					if ($detail['goods_id'] == $shopcar->spec->goods_id) {
						if ($detail['type'] == 1) {
							if ($detail['with_amount'] > $goods_amount) {
								//不满足
								$k->msg = '订单金额不满足满减金额';
								$invalid[] = $k;
							} else {
								//满足
								$k->msg = '666';
								$valid[] = $k;
							}
						} else {
							$k->msg = '666';
							$valid[] = $k;
						}
					} else {
						$k->msg = '不支持此商品';
						$invalid[] = $k;
					}
				} else {
					if ($detail['type'] == 1) {
						if ($detail['with_amount'] > $goods_amount) {
							//不满足
							$k->msg = '订单金额不满足满减金额';
							$invalid[] = $k;
						} else {
							//满足
							$k->msg = '666';
							$valid[] = $k;
						}
					} else {
						$k->msg = '666';
						$valid[] = $k;
					}
				}
			}
		}
		$this->writeJson(['valid' => $valid, 'invalid' => $invalid]);
	}
	
	
	/**
	 * 购物车价格计算
	 * @return void
	 */
	function shopcarGetPrice()
	{
		$shopcar_ids = $this->request->get('shopcar_ids');
		$coupon_id = $this->request->get('coupon_id/d', 0);
		$address = \app\model\Config::getFieldByName('address','value');
		$coupon = UserCoupon::find($coupon_id);
		$GoodsShopcar = GoodsShopcar::with(['goods', 'spec'])->whereIn('id', $shopcar_ids)->selectOrFail();
		$total_amount = '0';
		$coupon_amount = '0'; //优惠券金额
		$checkcoupon = false;
		foreach ($GoodsShopcar as $shopcar) {
			if ($shopcar->spec->sku < $shopcar->num) {
				$this->writeJson(0, '商品库存不足');
			}
			$total_amount = bcadd((string)$total_amount,bcmul((string)$shopcar->spec->price,(string)$shopcar->num,2),2);
			if (!empty($coupon)) {
				if ($checkcoupon) {
					//如果其中有一个商品验证通过  就不需要验证了
					continue;
				}
				$detail = $coupon->coupon;
				if ($coupon->expiretime <= time()) {
					$checkcoupon = false;
					continue;
				}
				if ($detail['scene'] == 1) {
					//指定商品
					if ($detail['goods_id'] == $shopcar->spec->goods_id) {
						if ($detail['type'] == 1) {
							if ($detail['with_amount'] > $shopcar->spec->price * $shopcar->num) {
								//不满足
								$checkcoupon = false;
							} else {
								$checkcoupon = true;
							}
						} else {
							$checkcoupon = true;
						}
					}
				} else {
					if ($detail['type'] == 1) {
						if ($detail['with_amount'] > $shopcar->spec->price * $shopcar->num) {
							//不满足
							$checkcoupon = false;
						} else {
							//满足
							$checkcoupon = true;
						}
					} else {
						$checkcoupon = true;
					}
				}
				
			}
		}
		if (!empty($coupon)) {
			if (!$checkcoupon) {
				$this->writeJson(0, '该优惠券不能使用');
			}
			$detail = $coupon->coupon;
			$coupon_amount = $detail['amount'];
		}
		$pay_amount = bcsub($total_amount,$coupon_amount,2);
		if ($pay_amount <= 0) {
			$pay_amount = 0.01;
		}
		
		$this->writeJson(['spec' => $GoodsShopcar,'address'=>$address, 'pay_amount' => $pay_amount, 'coupon_amount' => $coupon_amount, 'total_amount' => $total_amount]);
	}
	
	/**
	 * 购物车创建订单
	 * @return void
	 */
	function shopcarCreateOrder()
	{
		$shopcar_ids = $this->request->post('shopcar_ids');
		$pay_type = $this->request->post('pay_type/d');
		$take_delivery_id = $this->request->post('take_delivery_id/d');
		$coupon_id = $this->request->post('coupon_id/d', 0);
		$mark = $this->request->post('mark', '');
		$user = User::findOrFail($this->user_id);
		$coupon = UserCoupon::find($coupon_id);
		
		if (empty($take_delivery_id)) {
			$this->writeJson(0, '提货人不能为空');
		}
		$GoodsShopcar = GoodsShopcar::whereIn('id', $shopcar_ids)->selectOrFail();
		$total_amount = 0;
		$coupon_amount = 0; //优惠券金额
		$checkcoupon = false;
		$details = [];
		foreach ($GoodsShopcar as $shopcar) {
			if ($shopcar->spec->sku < $shopcar->num) {
				$this->writeJson(0, '商品库存不足');
			}
			$total_amount += $shopcar->spec->price * $shopcar->num;
			$details[] = [
				'goods_id' => $shopcar->goods_id,
				'spec_id' => $shopcar->spec_id,
				'amount' => $shopcar->spec->price * $shopcar->num,
				'num' => $shopcar->num,
			];
			
			if (!empty($coupon)) {
				if ($checkcoupon) {
					//如果其中有一个商品验证通过  就不需要验证了
					continue;
				}
				$detail = $coupon->coupon;
				if ($coupon->expiretime <= time()) {
					$checkcoupon = false;
					continue;
				}
				if ($detail['scene'] == 1) {
					//指定商品
					if ($detail['goods_id'] == $shopcar->spec->goods_id) {
						if ($detail['type'] == 1) {
							if ($detail['with_amount'] > $shopcar->spec->price * $shopcar->num) {
								//不满足
								$checkcoupon = false;
							} else {
								$checkcoupon = true;
							}
						} else {
							$checkcoupon = true;
						}
					}
				} else {
					if ($detail['type'] == 1) {
						if ($detail['with_amount'] > $shopcar->spec->price * $shopcar->num) {
							//不满足
							$checkcoupon = false;
						} else {
							//满足
							$checkcoupon = true;
						}
					} else {
						$checkcoupon = true;
					}
				}
			}
		}
		if (!empty($coupon)) {
			if (!$checkcoupon) {
				$this->writeJson(0, '该优惠券不能使用');
			}
			$detail = $coupon->coupon;
			$coupon_amount = $detail['amount'];
			$coupon->status = 2;
			$coupon->save();
		}
		$pay_amount = $total_amount - $coupon_amount;
		if ($pay_amount <= 0) {
			$pay_amount = 0.01;
		}
		
		
		$ordersn = Random::ordersn();
		// 启动事务
		Db::startTrans();
		try {
			$order = GoodsOrders::create([
				'user_id' => $this->user_id,
				'take_delivery_id' => $take_delivery_id,
				'coupon_id' => $coupon_id,
				'total_amount' => $total_amount, // 原价=商品价格*数量
				'pay_amount' => $pay_amount, //原价-优惠券金额
				'coupon_amount' => $coupon_amount,//优惠券金额
				'order_sn' => $ordersn,
				'mark' => $mark,
			]);
			
			$order->detail()->saveAll($details);
			$ret = Pay::pay($pay_type, $pay_amount, $ordersn, '购买商品', 'goods', $user->openid);
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			$this->writeJson(0, $e->getMessage());
		}
		//删除购物车
		$rows = GoodsShopcar::whereIn('id', $shopcar_ids)->selectOrFail(); //*****重新查询删除
		$rows->delete();
		
		Queue::later($this->order_timeout, Task::class, ['order_id' => $order->id, 'action' => 'goods_order_timeout'], 'task');
		$this->writeJson(['pay' => $ret, 'order_id' => $order->id]);
	}
	
	/**
	 * 订单列表
	 * @return void
	 */
	function orderList()
	{
		$status = $this->request->get('status/d'); // 0全部 1待付款 2待取货 3完成
		$rows = GoodsOrders::where(['user_id' => $this->user_id])
			->with(['detail' => function (Query $query) {
				$query->with(['goods', 'spec']);
			}])
			->when(!empty($status), function (Query $query) use ($status) {
				switch ($status) {
					case 1:
						$query->where(['pay_status' => 1]);
						break;
					case 2:
						$query->where(['pay_status' => 2]);
						break;
					case 3:
						$query->whereIn('pay_status', [3, 4]);
						break;
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	#订单详情
	function orderDetail()
	{
		$order_id = $this->request->get('order_id/d');
		$address = \app\model\Config::getFieldByName('address','value');
		
		$row = GoodsOrders::where(['user_id' => $this->user_id])
			->with(['detail' => function (Query $query){
				$query->with(['goods', 'spec']);
			}, 'take_delivery'])
			->filter(function ($data)use($address){
				$data->address = $address;
				if ($data->pay_status == 1){
					$data->canceltime_s = strtotime($data->createtime) + $this->order_timeout;
					$data->createtime_s = $data->getData('createtime');
				}
			})
			->findOrFail($order_id);
		$this->writeJson($row);
	}
	
	#订单详情列表
	function orderDetailList()
	{
		$order_id = $this->request->get('order_id/d');
		$rows = GoodsOrdersDetail::where(['order_id' => $order_id])
			->with(['goods','spec'])
			->select();
		$this->writeJson($rows);
		
	}
	
	#订单取消
	function orderCancel()
	{
		$order_id = $this->request->post('order_id/d');
		$row = GoodsOrders::where(['user_id' => $this->user_id, 'pay_status' => 1])->findOrFail($order_id);
		$row->pay_status = 5;
		$row->save();
		$this->writeJson();
	}
	
	#订单删除
	function orderDelete()
	{
		$order_id = $this->request->post('order_id/d');
		$row = GoodsOrders::where(['user_id' => $this->user_id, ['pay_status','in', [4,5]]])->findOrFail($order_id);
		$row->delete();
		$this->writeJson();
	}
	
	#订单支付
	function orderPay()
	{
		$order_id = $this->request->post('order_id/d');
		$pay_type = $this->request->post('pay_type/d');
		$row = GoodsOrders::where(['user_id' => $this->user_id, 'pay_status' => 1])->findOrFail($order_id);
		$user = User::findOrFail($this->user_id);
		$ordersn = Random::ordersn();
		// 启动事务
		Db::startTrans();
		try {
			$row->order_sn = $ordersn;
			$row->save();
			$ret = Pay::pay($pay_type, $row->pay_amount, $ordersn, '购买商品', 'goods', $user->openid);
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			$this->writeJson(0, $e->getMessage());
		}
		$this->writeJson($ret);
	}
	
	#订单确认
	function orderConfirm()
	{
		$order_id = $this->request->post('order_id/d');
		$row = GoodsOrders::where(['user_id' => $this->user_id])->findOrFail($order_id);
		if ($row->pay_status != 2) {
			$this->writeJson(0, '订单状态异常');
		}
		
		$score = \app\model\Config::getFieldByName('score', 'value');
		$score = bcmul((string)$score , (string)$row->pay_amount,2);
		try {
			UserService::changeUserScore($score, $row->user_id, '确认收货积分奖励');
			$row->pay_status = 3;
			$row->save();
		} catch (\Exception $e) {
			$this->writeJson(0, $e->getMessage());
		}
		
		$this->writeJson(101, "获得{$score}积分奖励");
	}
	
	#订单评价
	function orderAssess()
	{
		$order_detail_id = $this->request->post('order_detail_id/d');
		$score = $this->request->post('score/d', 5);
		$images = $this->request->post('images', '');
		$content = $this->request->post('content', '');
		$anonymous = $this->request->post('anonymous/d', 1);
		if (!$content) {
			$this->writeJson(0, '评论内容不能为空');
		}
		$orderDetail = GoodsOrdersDetail::findOrFail($order_detail_id);
		
		GoodsAssess::create([
			'user_id' => $this->user_id,
			'goods_id' => $orderDetail->goods_id,
			'order_detail_id' => $orderDetail->id,
			'spec_id' => $orderDetail->spec_id,
			'score' => $score,
			'images' => $images,
			'content' => $content,
			'anonymous' => $anonymous,
		]);
		$orderDetail->assess = 1;
		$assess = $orderDetail->orders->detail()->where(['assess'=>2,['id','<>',$orderDetail->id]])->find();
		if (!$assess){
			$orderDetail->orders->pay_status = 4;
		}
		$orderDetail->together(['orders'])->save();
		$this->writeJson();
	}
	
	#管理员订单列表
	function adminOrderList()
	{
		Log::record('管理员订单列表');
		$status = $this->request->get('status/d'); // 1待取货  2已完成
		$user = User::find($this->user_id);
		if (!$user){
			$this->writeJson(401, '重新登陆');
		}
		if ($user->type!=2){
			$this->writeJson(0, '你没有核销权限');
		}
		$rows = GoodsOrders::with(['detail' => function (Query $query) {
				$query->with(['goods', 'spec']);
			},'take_delivery'])
			->when(!empty($status), function (Query $query) use ($status) {
				switch ($status) {
					case 1:
						$query->where(['pay_status' => 2]);
						break;
					case 2:
						$query->whereIn('pay_status', [3, 4]);
						break;
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	#订单确认
	function adminOrderConfirm()
	{
		
		$order_id = $this->request->post('order_id/d');
		$user = User::find($this->user_id);
		if (!$user){
			$this->writeJson(401, '重新登陆');
		}
		if ($user->type!=2){
			$this->writeJson(0, '你没有核销权限');
		}
		$row = GoodsOrders::findOrFail($order_id);
		if ($row->pay_status != 2) {
			$this->writeJson(0, '订单状态异常');
		}
		$row->pay_status = 3;
		$row->save();
		$this->writeJson();
	}
	
	#订单删除
	function adminOrderDelete()
	{
		$order_id = $this->request->post('order_id/d');
		$user = User::find($this->user_id);
		if (!$user){
			$this->writeJson(401, '重新登陆');
		}
		if ($user->type!=2){
			$this->writeJson(0, '你没有核销权限');
		}
		$row = GoodsOrders::where([['pay_status','in', [4,5]]])->findOrFail($order_id);
		$row->delete();
		$this->writeJson();
	}
	
	
}
